﻿using Abp.AutoMapper;
using Abp.Modules;
using Abp.Reflection.Extensions;
using ALEXFW.Authorization;
using ALEXFW.Configuration;
using ALEXFW.Login.Dto;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Text;

namespace ALEXFW
{
    [DependsOn(
        typeof(ALEXFWCoreModule), 
        typeof(AbpAutoMapperModule))]
    public class ALEXFWApplicationModule : AbpModule
    {
        private readonly IWebHostEnvironment _env;
        private readonly IConfigurationRoot _appConfiguration;

        public ALEXFWApplicationModule(IWebHostEnvironment env)
        {
            _env = env;
            _appConfiguration = AppConfigurations.Get(env.ContentRootPath, env.EnvironmentName, env.IsDevelopment());
        }
        public override void PreInitialize()
        {
            Configuration.Authorization.Providers.Add<ALEXFWAuthorizationProvider>();
        }

        public override void Initialize()
        {
            var thisAssembly = typeof(ALEXFWApplicationModule).GetAssembly();

            IocManager.RegisterAssemblyByConvention(thisAssembly);

            Configuration.Modules.AbpAutoMapper().Configurators.Add(
                // Scan the assembly for classes which inherit from AutoMapper.Profile
                cfg => cfg.AddMaps(thisAssembly)
            );

            ConfigrationToken();
        }

        private void ConfigrationToken()
        {
            IocManager.Register<TokenConfiguration>();
            var tokenAuthConfig = IocManager.Resolve<TokenConfiguration>();

            tokenAuthConfig.SecurityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_appConfiguration["Authentication:JwtBearer:SecurityKey"]));
            tokenAuthConfig.Issuer = _appConfiguration["Authentication:JwtBearer:Issuer"];
            tokenAuthConfig.Audience = _appConfiguration["Authentication:JwtBearer:Audience"];
            tokenAuthConfig.SigningCredentials = new SigningCredentials(tokenAuthConfig.SecurityKey, SecurityAlgorithms.HmacSha256);
            tokenAuthConfig.Expiration = TimeSpan.FromHours(1);
        }
    }
}
